package com.tianji.aigc.service.impl;

import cn.hutool.core.util.IdUtil;
import com.tianji.aigc.properties.SessionProperties;
import com.tianji.aigc.entity.ChatSession;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.service.IChatSessionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.vo.SessionVO;
import com.tianji.common.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 对话session 服务实现类
 * </p>
 *
 * @author fzk
 * @since 2025-09-02
 */
@Service
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements IChatSessionService {

    @Autowired
    private SessionProperties sessionProperties;



    /**
     * 新建会话
     */
    @Override
    public SessionVO createSession(Integer number) {
        //1. 生成会话id
        String sessionId = IdUtil.fastSimpleUUID();//使用UUID生成会话ID

        //2. 保存会话历史
        ChatSession session = ChatSession.builder()
                .sessionId(sessionId)//会话id
                .userId(UserContext.getUser())//用户id
                .build();
        this.save(session);

        //3. 随机取出三个热门问题
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        Collections.shuffle(examples);//打乱集合顺序
        List<SessionVO.Example> exampleList = examples.stream().limit(number).toList();

        //4. 封装结果
        SessionVO sessionVO = SessionVO.builder()
                .sessionId(sessionId)//会话id
                .title(sessionProperties.getTitle())//默认标题
                .describe(sessionProperties.getDescribe())//默认描述
                .examples(exampleList)//随机话题
                .build();
        return sessionVO;
    }

    /**
     * 获取随机热点
     */
    @Override
    public List<SessionVO.Example> getHotExampleList(Integer number) {
        // 随机取出三个热门问题
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        Collections.shuffle(examples);//打乱集合顺序
        List<SessionVO.Example> exampleList = examples.stream().limit(number).toList();
        return exampleList;
    }
}
